/*
 * Service class 
 * Created on 6 juin 2013 ( Time 15:03:32 )
 */

package org.demo.employe.service;

import java.util.List;

import org.demo.employe.bean.Employe;
import org.demo.employe.dao.JpaEmployeDAO;
import org.telosys.starterkits.strutsjpa.EntityManagerHelper;
import org.telosys.starterkits.strutsjpa.IServices;
import javax.persistence.PersistenceException;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;


public class EmployeServices implements IServices<Employe, Integer> {

	protected final Logger LOG = LoggerFactory.getLogger(EmployeServices.class);

	public Employe load(final Integer id) {
		if (LOG.isDebugEnabled()) LOG.debug("load");
		Employe employe;
		try {
			EntityManagerHelper.beginTransaction();
			JpaEmployeDAO employeDAO = new JpaEmployeDAO();
			employe = employeDAO.findById(id);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return employe ;
	}

	public Employe save(final Employe entity) {
		if (LOG.isDebugEnabled()) LOG.debug("save");
		Employe entityNew;
		try {
			EntityManagerHelper.beginTransaction();
			JpaEmployeDAO employeDAO = new JpaEmployeDAO();
			entityNew = employeDAO.update(entity);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return entityNew;
	}

	public void delete(final Integer id) {
		if (LOG.isDebugEnabled()) LOG.debug("delete");
		try {
			EntityManagerHelper.beginTransaction();
			JpaEmployeDAO employeDAO = new JpaEmployeDAO();
			employeDAO.delete(id);
			EntityManagerHelper.commitAndCloseEntityManager();	
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
	}

	public List<Employe> search(final Employe employe) {
		if (LOG.isDebugEnabled()) LOG.debug("search");
		List<Employe> liste;
		try {
			EntityManagerHelper.beginTransaction();
			JpaEmployeDAO employeDAO = new JpaEmployeDAO();
			liste = employeDAO.search(employe);
			EntityManagerHelper.commitAndCloseEntityManager();
		} catch (PersistenceException ex) {
			LOG.error("Error", ex);
			throw ex;
		} finally {
			if (EntityManagerHelper.isCloseEntityManager() == false) EntityManagerHelper.rollback();
		}
		return liste;
	}

}
